<template>
  <div class="favorites-page">
    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索收藏的资源..."
          size="large"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" size="large" @click="handleSearch">
          搜索
        </el-button>
      </div>
      
      <div class="filter-bar">
        <el-select v-model="categoryFilter" placeholder="选择分类" clearable @change="handleFilter">
          <el-option
            v-for="category in categories"
            :key="category.categoryId"
            :label="category.categoryName"
            :value="category.categoryId"
          />
        </el-select>
        
        <el-select v-model="typeFilter" placeholder="文件类型" clearable @change="handleFilter">
          <el-option label="PDF" value="pdf" />
          <el-option label="Word" value="docx" />
          <el-option label="PowerPoint" value="pptx" />
          <el-option label="视频" value="mp4" />
          <el-option label="音频" value="mp3" />
        </el-select>
        
        <el-button @click="refreshFavorites" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        
        <el-button 
          v-if="selectedFavorites.length > 0" 
          type="danger" 
          @click="batchRemoveFavorites"
        >
          <el-icon><Delete /></el-icon>
          批量移除 ({{ selectedFavorites.length }})
        </el-button>
      </div>
    </div>

    <!-- 收藏列表 -->
    <div class="favorites-content">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>

      <div v-else-if="favorites.length === 0" class="empty-state">
        <el-icon class="empty-icon"><StarFilled /></el-icon>
        <h3>暂无收藏</h3>
        <p>去<router-link to="/resources">学习资源</router-link>页面收藏喜欢的内容吧！</p>
      </div>

      <div v-else class="favorites-list">
        <div 
          v-for="favorite in favorites" 
          :key="favorite.id"
          class="favorite-item"
          @click="viewResource(favorite.resource)"
        >
          <div class="item-content">
            <h4 class="resource-title">{{ favorite.resource.title }}</h4>
            <p class="resource-desc">{{ favorite.resource.description }}</p>
            
            <div class="item-meta">
              <span class="meta-item">{{ favorite.resource.categoryName }}</span>
              <span class="meta-item">{{ favorite.resource.uploaderName }}</span>
              <span class="meta-item">{{ formatDate(favorite.createdAt) }}</span>
            </div>
          </div>
          
          <div class="item-actions">
            <el-button type="primary" size="small">下载</el-button>
            <el-button type="danger" size="small" @click.stop="removeFavorite(favorite)">移除</el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Delete,
  StarFilled,
  Document,
  VideoPlay,
  Headset,
  FolderOpened,
  User,
  Download,
  Clock
} from '@element-plus/icons-vue'
import favoriteApi from '@/api/favorite'

export default {
  name: 'UserFavorites',
  components: {
    Search,
    Refresh,
    Delete,
    StarFilled,
    Document,
    VideoPlay,
    Headset,
    FolderOpened,
    User,
    Download,
    Clock
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    
    const loading = ref(false)
    const favorites = ref([])
    const categories = ref([])
    const selectedFavorites = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(20)
    
    // 搜索和筛选
    const searchKeyword = ref('')
    const categoryFilter = ref('')
    const typeFilter = ref('')
    
    // 计算属性
    const isLoggedIn = computed(() => store.getters.getLoginStatus)
    
    // 方法
    const loadFavorites = async () => {
      if (!isLoggedIn.value) {
        router.push('/login')
        return
      }
      
      loading.value = true
      try {
        const params = {
          current: currentPage.value,
          size: pageSize.value,
          keyword: searchKeyword.value,
          categoryId: categoryFilter.value,
          fileType: typeFilter.value
        }
        
        const response = await favoriteApi.getUserFavorites(params)
        
        // 处理后端返回的数据结构 - 支持多种格式
        let pageResult = response.data || response || {}
        let rawData = []
        
        if (Array.isArray(pageResult)) {
          // 如果直接返回数组
          rawData = pageResult
          total.value = pageResult.length
        } else if (pageResult.records && Array.isArray(pageResult.records)) {
          // 如果是PageResult格式
          rawData = pageResult.records
          total.value = pageResult.total || 0
        } else if (pageResult.list && Array.isArray(pageResult.list)) {
          // 如果是list格式
          rawData = pageResult.list
          total.value = pageResult.total || pageResult.count || pageResult.list.length
        } else {
          // 处理其他格式
          rawData = []
          total.value = 0
        }
        
        favorites.value = rawData.map(item => {
          const favorite = {
            id: item.id || item.favoriteId,
            resourceId: item.resourceId || item.resource_id,
            createdAt: item.createdAt || item.created_at,
            resource: {
              resourceId: item.resourceId || item.resource_id,
              title: item.resourceTitle || item.resource_title || item.title || '未知标题',
              description: item.description || '暂无描述',
              fileType: item.fileType || item.file_type,
              fileSize: item.fileSize || item.file_size,
              categoryName: item.categoryName || item.category_name || '未分类',
              uploaderName: item.uploaderName || item.uploader_name || '未知用户',
              downloadCount: item.downloadCount || item.download_count || 0,
              viewCount: item.viewCount || item.view_count || 0,
              rating: item.rating || 0,
              uploadTime: item.uploadTime || item.upload_time
            }
          }
          
          return favorite
        })
      } catch (error) {
        console.error('加载收藏失败:', error)
        ElMessage.error('加载收藏失败: ' + (error.message || '请稍后重试'))
        
        // 清空收藏列表，不使用模拟数据
        favorites.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }
    
    const loadCategories = async () => {
      try {
        // 这里应该调用分类API
        categories.value = [
          { categoryId: 1, categoryName: '编程开发' },
          { categoryId: 2, categoryName: '设计创意' },
          { categoryId: 3, categoryName: '数据科学' },
          { categoryId: 4, categoryName: '产品运营' },
          { categoryId: 5, categoryName: '语言学习' },
          { categoryId: 6, categoryName: '职业技能' }
        ]
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    }
    
    const handleSearch = () => {
      currentPage.value = 1
      loadFavorites()
    }
    
    const handleFilter = () => {
      currentPage.value = 1
      loadFavorites()
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadFavorites()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadFavorites()
    }
    
    const refreshFavorites = () => {
      loadFavorites()
    }
    
    const viewResource = (resource) => {
      router.push(`/resources/${resource.resourceId}`)
    }
    
    const downloadResource = async (resource) => {
      try {
        // 这里应该调用下载API
        ElMessage.success('开始下载...')
      } catch (error) {
        console.error('下载失败:', error)
        ElMessage.error('下载失败，请稍后重试')
      }
    }
    
    const removeFavorite = async (favorite) => {
      try {
        await ElMessageBox.confirm(
          '确定要移除这个收藏吗？',
          '确认移除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 获取resourceId - 支持多种数据结构
        let resourceId = null
        
        if (favorite.resourceId) {
          resourceId = favorite.resourceId
        } else if (favorite.resource && favorite.resource.resourceId) {
          resourceId = favorite.resource.resourceId
        } else if (favorite.resource_id) {
          resourceId = favorite.resource_id
        }
        
        if (!resourceId) {
          // 无法获取资源ID错误日志已移除
          throw new Error('无法获取资源ID，请刷新页面后重试')
        }
        
                  // 准备移除收藏日志已移除
        await favoriteApi.removeFavorite(resourceId)
        
        ElMessage.success('移除成功')
        // 立即从列表中移除该项，提升用户体验
        favorites.value = favorites.value.filter(item => 
          (item.resourceId || item.resource?.resourceId) !== resourceId
        )
        total.value = Math.max(0, total.value - 1)
        
        // 然后刷新列表确保数据一致性
        loadFavorites()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('移除收藏失败:', error)
          ElMessage.error(error.message || '移除失败，请稍后重试')
        }
      }
    }
    
    const batchRemoveFavorites = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要移除选中的 ${selectedFavorites.value.length} 个收藏吗？`,
          '批量移除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await favoriteApi.batchRemoveFavorites(selectedFavorites.value)
        ElMessage.success('批量移除成功')
        selectedFavorites.value = []
        loadFavorites()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量移除失败:', error)
          ElMessage.error('移除失败，请稍后重试')
        }
      }
    }
    
    const getFileIconClass = (fileType) => {
      if (!fileType) return 'file-icon-default'
      const type = fileType.toLowerCase()
      if (['pdf'].includes(type)) return 'file-icon-pdf'
      if (['doc', 'docx'].includes(type)) return 'file-icon-word'
      if (['ppt', 'pptx'].includes(type)) return 'file-icon-ppt'
      if (['mp4', 'avi', 'mkv'].includes(type)) return 'file-icon-video'
      if (['mp3', 'wav'].includes(type)) return 'file-icon-audio'
      return 'file-icon-default'
    }
    
    const getCategoryTagType = (category) => {
      const typeMap = {
        '编程开发': 'primary',
        '设计创意': 'success',
        '数据科学': 'warning',
        '产品运营': 'info',
        '语言学习': 'danger'
      }
      return typeMap[category] || 'primary'
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }
    
    // 生命周期
    onMounted(() => {
      loadCategories()
      loadFavorites()
    })
    
    return {
      // 响应式数据
      loading,
      favorites,
      categories,
      selectedFavorites,
      total,
      currentPage,
      pageSize,
      searchKeyword,
      categoryFilter,
      typeFilter,
      
      // 计算属性
      isLoggedIn,
      
      // 方法
      handleSearch,
      handleFilter,
      handleSizeChange,
      handleCurrentChange,
      refreshFavorites,
      viewResource,
      downloadResource,
      removeFavorite,
      batchRemoveFavorites,
      getFileIconClass,
      getCategoryTagType,
      formatDate
    }
  }
}
</script>

<style scoped>
.favorites-page {
  padding: 24px;
}

/* 搜索和筛选 */
.filter-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
}

.search-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.search-bar .el-input {
  flex: 1;
}

.filter-bar {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-bar .el-select {
  width: 150px;
}

/* 收藏列表 */
.favorites-content {
  background: white;
  border-radius: 12px;
  padding: 24px;
  border: 1px solid #e4e7ed;
}

.loading-container {
  padding: 40px 0;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  color: #dcdfe6;
}

.empty-state h3 {
  margin: 0 0 12px 0;
  font-size: 18px;
  color: #606266;
}

.empty-state a {
  color: #409eff;
  text-decoration: none;
}

.favorites-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.favorite-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s ease;
}

.favorite-item:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.item-content {
  flex: 1;
}

.resource-title {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.resource-desc {
  margin: 0 0 12px 0;
  color: #606266;
}

.item-meta {
  display: flex;
  gap: 16px;
}

.meta-item {
  color: #909399;
  font-size: 14px;
}

.item-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
  }
  
  .filter-bar {
    flex-wrap: wrap;
  }
  
  .favorite-item {
    flex-direction: column;
    align-items: stretch;
  }
  
  .item-meta {
    flex-direction: column;
    gap: 8px;
  }
  
  .item-actions {
    flex-direction: row;
  }
}
</style> 